// Fill out your copyright notice in the Description page of Project Settings.


#include "NetworkTool/CommonNetworkTool.h"

#include "Interfaces/IHttpResponse.h"
#ifdef __unix
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#else
#ifdef _WIN32
#include "Windows/AllowWindowsPlatformTypes.h"
#include <wininet.h>
#pragma comment(lib, "Wininet.lib")
#include "Windows/HideWindowsPlatformTypes.h"
#endif
#endif

UCommonNetworkTool::UCommonNetworkTool()
{
	HttpRequest = HttpRequest = FHttpModule::Get().CreateRequest();
	APIResStateCode = 0;
}

bool UCommonNetworkTool::IsNetworkConnected() const
{
#ifdef __unix
	// 创建一个套接字
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd == -1) {
		std::cerr << "Error creating socket." << std::endl;
		return false;
	}

	// 设置服务器信息
	struct sockaddr_in server;
	server.sin_family = AF_INET;
	server.sin_port = htons(80); // HTTP默认端口
	inet_pton(AF_INET, "8.8.8.8", &server.sin_addr); // 使用Google的公共DNS服务器

	// 尝试连接
	int result = connect(sockfd, (struct sockaddr*)&server, sizeof(server));
	close(sockfd);

	if (result == 0) {
		return true; // 连接成功，网络通畅
	} else {
		return false; // 连接失败，网络不通
	}
#else
#ifdef _WIN32
	return InternetGetConnectedState(NULL, 0);
#endif
#endif
}

void UCommonNetworkTool::RunApi(const FString& APIAddress)
{
	HttpRequest->SetVerb(L"POST");
	HttpRequest->SetHeader("Content-Type", "application/json;charset=UTF-8");
	
	// Apply params
	HttpRequest->SetURL(APIAddress);

	HttpRequest.Get()->OnProcessRequestComplete().BindUObject(this, &UCommonNetworkTool::OnApiResult);
	// Execute the request
	HttpRequest->ProcessRequest();
}

void UCommonNetworkTool::GetApiState(int32& APIState) const
{
	APIState = APIResStateCode;
}

void UCommonNetworkTool::GetApiResult(FString& ResultContent, int32& APIState)
{
	ResultContent = APIResultStr;
	GetApiState(APIState); 
}

void UCommonNetworkTool::OnApiResult(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
	if (!HttpRequest.IsValid() || !Response.IsValid())
	{
		return;
	}

	APIResultStr = Response->GetContentAsString();
	APIResStateCode = Response->GetResponseCode();
}
